package cn.tedu.demo.service.impl;

import cn.tedu.demo.ex.ServiceException;
import cn.tedu.demo.mapper.OrderInfoMapper;
import cn.tedu.demo.mapper.RoomListMapper;
import cn.tedu.demo.mapper.RoomStaMapper;
import cn.tedu.demo.pojo.dto.OrderAddNewDTO;
import cn.tedu.demo.pojo.entity.OrderInfo;
import cn.tedu.demo.pojo.entity.RoomSta;
import cn.tedu.demo.pojo.vo.*;
import cn.tedu.demo.service.IOrderInfoService;
import cn.tedu.demo.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class OrderInfoImpl implements IOrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private RoomStaMapper roomStaMapper;
    @Autowired
    private RoomListMapper roomListMapper;


    @Override
    public void addNew(OrderAddNewDTO orderAddNewDTO, HttpSession session) {
        log.debug("开始处理【添加订单】的业务，参数：{}", orderAddNewDTO);
        //通过入参对象获得roomSta查询需要的参数
        Integer roomTypeId = orderAddNewDTO.getRoomTypeId();
        Date checkinDateDTO=orderAddNewDTO.getCheckinDate();
        Date checkoutDateDTO=orderAddNewDTO.getCheckoutDate();
        Long bookingDays=(checkoutDateDTO.getTime()-checkinDateDTO.getTime())/(24*60*60*1000);
        log.debug("入参计算的入住天数：{}", bookingDays);
        // 通过入住天数和对应时间判断逻辑,写出不满足入住的请情况抛出异常
        //调用roomStaMapper.getByCanBookMin获取roomStaVO对象,该对象为符合时间和房型条件的对象
        RoomStaRoomNumCanBookDaysVO currentRoomCanBookDays = roomStaMapper.getCanBookRoomNumByTypeIdDate(
                roomTypeId,checkinDateDTO,checkoutDateDTO);
        log.debug("currentRoomCanBookDays：{}", currentRoomCanBookDays);
        //判断符合条件的对象是否存在
        if(currentRoomCanBookDays==null){
            String message="该时间段房间已满,请重新选择时间或房型!";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //通过合服条件的对象判断
        Long canBookDays = currentRoomCanBookDays.getCanBookDays()+0L;
            //判断预定天数是否大于可定天数,是则抛出异常,提示房间已满
        if(bookingDays>canBookDays){
            String message="该时间段房间已满,请重新选择时间或房型!";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }

        // 否则
        //创建实体类对象,补充完数据后,准备调用mapper接口插入数据库
        OrderInfo orderInfo=new OrderInfo();
        //复制入参数据到实体类
        BeanUtils.copyProperties(orderAddNewDTO,orderInfo);
        //根据登录的session获取当前用户VO对象(其中id,tel字段可用).
        log.debug("验证session信息,session:{}",session);
        UserVO currentUser=(UserVO) session.getAttribute("user");
        orderInfo.setUserId(currentUser.getId());
        orderInfo.setOrderTel(currentUser.getTel());
        //设置订单状态
        orderInfo.setOrderStatus("生效中");
        //设置订单生成时间
        orderInfo.setBookDate(LocalDateTime.now());

        //通过查找自动分配到的房间号,找到对应的房间类型ID和房间类型名称
        String roomNum=currentRoomCanBookDays.getRoomNum();
        orderInfo.setRoomTypeNum(roomNum);
        //通过房号获取currentRoomStandard对象
        RoomStandardVO currentRoomStandard = roomListMapper.getRoomStandardByNum(roomNum);
        String roomTypeName = currentRoomStandard.getRoomTypeName();
        String roomTypeNum = currentRoomStandard.getRoomTypeNum();
//        通过.getNum获取具体客房编号roomTypeName
        orderInfo.setRoomTypeName(roomTypeName);
//        通过.getNum获取具体客房编号roomTypeName
        orderInfo.setRoomTypeNum(roomTypeNum);
        log.debug("即将插入对象:"+orderInfo);
        //调用mapper生成新的订单,插入数据库
        int rows = orderInfoMapper.insert(orderInfo);
        if (rows != 1) {
            String message = "订单生成失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        //修改room_sta中相应时间的房间状态
        //TODO 通过room_num 和state_date 查询到相应的 state_id,判断是否为1,不是则抛异常(省略)
        //是则状态修改为0
        rows = roomStaMapper.setState(roomNum, RoomSta.CAN_NOT_BOOK, checkinDateDTO, checkoutDateDTO);
        if (rows <bookingDays) {
            String message = "订单生成失败，服务器忙(房间状态修改失败)，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public List<OrderInfoListVO> listByOrderTel(HttpSession session) {

        //根据登录的session获取当前用户VO对象(其中id,tel字段可用).
        UserVO currentUser=(UserVO) session.getAttribute("user");
        //通过session获取到的用户，的到其中的电话号码
        String orderTel=currentUser.getTel();
        log.debug("开始执行【根据预订号码查询订单】的业务，参数：{}",orderTel);
        //通过此电话号码，调用mapper查询数据库中的订单表格
        List<OrderInfoListVO> queryList = orderInfoMapper.listByOrderTel(orderTel);
        //返回查询到的订单列表
        return queryList;
    }
}
